//
//  USPhotoController.m
//  us
//
//  Created by karry on 2025/4/8.
//

#import "USPhotoController.h"
#import "USAddPhotoAlbumController.h"
#import "USZoomFlowLayout.h"
#import "USAlbumCell.h"
#import "USAlbumPhotoListController.h"
#import "USAlertTipBar.h"
#import "AlbumStorage.h"
#import "USAlbumEditController.h"
#import "USPhotoModel.h"
@interface USPhotoController ()<UICollectionViewDelegate,UICollectionViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray *list;
@property (nonatomic,strong) USShareSpaceModel *spaceModel;

@property (nonatomic,strong) UIBarButtonItem *leftTitleItem;

@property (nonatomic,strong) UILabel *titleLab;

@property (nonatomic,strong) USAlertTipBar *tipBar;

@property (nonatomic,strong) UIButton *moreBtn;

@property (nonatomic,copy) NSString *n_albumId;

@property (nonatomic,strong) NSIndexPath *selectIndexPath;

@end

@implementation USPhotoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"us 相册";
    
    self.navigationItem.leftBarButtonItem = self.leftTitleItem;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
    
    self.displayEmptySet = NO;
    
    self.view.clipsToBounds = YES;

    [self setupView];
    
    @weakify(self)
    [[NSNotificationCenter defaultCenter]addObserverForName:@"USNotificationNameAddAlbumSuccess" object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull notification) {
        @strongify(self)
        self.n_albumId = notification.object;
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}


- (void)loadData{
    [super loadData];
    
    self.list = [[[AlbumStorage shared]fetchLocalAlbums] mutableCopy];
    
//    self.moreBtn.hidden = self.list.count>0?NO:YES;
    if (self.list.count > 0) {
        self.moreBtn.hidden = NO;
    }else{
        self.moreBtn.hidden = YES;
    }

    [self.collectionView reloadData];
    
    [self.collectionView reloadEmptyDataSet];
    
    [self reloadTipBarHiiden];
    
    [self updateRemoteData];

    [self getShareSpace];
}

- (void)reloadTipBarHiiden{
    
    self.tipBar.hidden = self.list.count > 0?NO:YES;
    if (self.list.count > 0) {
        if (self.selectIndexPath && self.list.count > self.selectIndexPath.row) {
            Album *record = self.list[self.selectIndexPath.row];
            self.navigationItem.title = record.albumName;
        }else{
            Album *record = self.list[[self c_indexPath].row];
            self.navigationItem.title = record.albumName;
        }
      
    }else{
        self.navigationItem.title = @"us相册";
    }
    
}

- (void)scrollToNewAlbumIfNeed{
    
    if (!self.n_albumId) {
        return;
    }
    
    [self.collectionView layoutIfNeeded];
    
    for (NSInteger i = 0; i < self.list.count; i++) {
        
        Album *model = self.list[i];
        
        NSLog(@"%@ - %@ ",model.albumId,self.n_albumId);
        
        if ([model.albumId isEqualToString:self.n_albumId]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            break;
        }
    }
    self.n_albumId = nil;
    
}


//刷新远程数据
- (void)updateRemoteData{
    
    
    [[EMNetWork shareManager] em_post:API_AlbumList
                               params:@{@"sharedSpaceId":USUser.user.sharedSpaceId?:@""}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        
        NSArray *list = api.data[@"albumList"];
        self.list = [[[AlbumStorage shared]syncRemoteAlbums:list] mutableCopy];
        [self.collectionView reloadData];
        [self.collectionView reloadEmptyDataSet];
        [self reloadTipBarHiiden];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self scrollToNewAlbumIfNeed];
        });
        
    } fail:^{
        
        
    }];
    
    
}

- (void)getShareSpace{

    [[EMNetWork shareManager] em_post:API_SharedSpaceInfo
                               params:@{}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
 
        self.spaceModel = [USShareSpaceModel mj_objectWithKeyValues:api.data[@"sharedSpace"]];
        
        self.tipBar.subLab.text = [NSString stringWithFormat:@"%iM/500M",MIN((int)self.spaceModel.albumStorageSize, 500)] ;
        
    } fail:^{
        
        
    }];
    
    
}


- (void)setupView{
    
    USZoomFlowLayout *layout = [USZoomFlowLayout new];
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.clearColor;
    _collectionView = collectionView;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.decelerationRate = UIScrollViewDecelerationRateFast; // 更快速吸附居中
    collectionView.pagingEnabled = NO; // 不要分页，否则失效
    collectionView.emptyDataSetSource = self;
    collectionView.emptyDataSetDelegate = self;
    collectionView.delaysContentTouches = YES;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerClass:[USAlbumCell class] forCellWithReuseIdentifier:@"USAlbumCellId"];
    collectionView.layer.masksToBounds = NO;
//    collectionView.clipsToBounds = YES;
    collectionView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:collectionView];
    
    CGFloat h = layout.suggestSize.height;
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(h);
        make.left.right.mas_offset(0);
        make.centerY.mas_equalTo(self.view.mas_centerY).mas_offset(-30);
    }];
    
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _moreBtn = moreBtn;
    _moreBtn.hidden = YES;
    [moreBtn addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    [moreBtn setImage:[UIImage imageNamed:@"ic_more"] forState:0];
    [self.view addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-55 - 12);
        make.top.mas_equalTo(collectionView.mas_bottom).mas_offset(16);
    }];
    
    
    USAlertTipBar *tipBar = [[USAlertTipBar alloc]initWithFrame:CGRectZero];
    _tipBar = tipBar;
    _tipBar.hidden = YES;
    tipBar.style = USAlertTipBarStyleDefault;
    tipBar.color = UIColor.us_yellowColor;
    tipBar.titleLab.text = @"免费容量";
    tipBar.subLab.text = @"0M/500M";
    
    [self.view addSubview:tipBar];
    [tipBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(60);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-12);
    }];
    
}

- (void)moreAction:(UIButton *)sender{
    
    
    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"置顶" image:[UIImage imageNamed:@"icon-top-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self makeAlbumTop];
    }];
    DTItem *item1 = [DTItem itemWithTitle:@"编辑" image:[UIImage imageNamed:@"icon-edit-22"] tag:1 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self editAlbum];
    }];
    
    DTItem *item2 = [DTItem itemWithTitle:@"删除" image:[UIImage imageNamed:@"icon-trash-22"] tag:2 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self prepareDeleteAlbum];
    }];
    DTTargetView *targetView = [[DTTargetView alloc]initWithTargetView:sender item:@[item0,item1,item2]];
    [targetView show];
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self updateCurrentCenteredAlbumTitle];
}

- (void)updateCurrentCenteredAlbumTitle {
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width / 2.0;
    NSArray *visibleCells = [self.collectionView visibleCells];

    NSIndexPath *centerIndexPath = nil;
    CGFloat minDelta = CGFLOAT_MAX;

    for (UICollectionViewCell *cell in visibleCells) {
        CGFloat delta = fabs(centerX - cell.center.x);
        if (delta < minDelta) {
            minDelta = delta;
            centerIndexPath = [self.collectionView indexPathForCell:cell];
        }
    }

    if (centerIndexPath && centerIndexPath.item < self.list.count) {
        Album *record = self.list[centerIndexPath.item];
        if (![self.navigationItem.title isEqualToString:record.albumName]) {
            self.navigationItem.title = record.albumName;
            [USFeedbackTool selectionChanged]; // 如果不想频繁反馈也可以去掉
            
        }
    }
}


- (void)addAction:(id)sender{
    
    [USFeedbackTool impactMedium];
    USAddPhotoAlbumController *vc = [USAddPhotoAlbumController new];
    DTNavigationController *navc = [[DTNavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navc animated:YES completion:nil];
    
}

#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [USFeedbackTool impactSoft];
    USAlbumPhotoListController *vc = [[USAlbumPhotoListController alloc]init];
    NSIndexPath *currentIndexPath = [self c_indexPath];
    self.selectIndexPath = currentIndexPath;
    if (currentIndexPath) {
        Album *album = self.list[currentIndexPath.item];
        vc.albumId = album.albumId;
        vc.albumFirstDirectory = album.albumFirstDirectory;
        vc.albumSecondDirectory = album.albumSecondDirectory;
        vc.album = album;
        vc.title = album.albumName;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.list.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    USAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USAlbumCellId" forIndexPath:indexPath];
    
    Album *record = self.list[indexPath.row];
    
    cell.coverView.bgImageView.hidden = NO;
    
    cell.coverView.color = [UIColor jk_colorWithHexString:record.color];
    
    cell.coverView.lineImageView.hidden = record.coverType == 0 ? NO : YES;

    NSLog(@"%@",record.coverUrl);
    
    [cell.coverView.bgImageView sd_setImageWithURL:[NSURL URLWithString:record.coverUrl]placeholderImage:nil];
    
    cell.coverView.bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    NSLog(@"%@",record.color);
    
    return cell;
    
}

- (NSIndexPath *) c_indexPath {
    
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width / 2.0;
    
    NSArray<UICollectionViewCell *> *visibleCells = [self.collectionView visibleCells];
    NSIndexPath *targetIndexPath = nil;
    CGFloat minDelta = CGFLOAT_MAX;
    
    for (UICollectionViewCell *cell in visibleCells) {
        CGFloat delta = fabs(centerX - cell.center.x);
        if (delta < minDelta) {
            minDelta = delta;
            targetIndexPath = [self.collectionView indexPathForCell:cell];
        }
    }
    
    return targetIndexPath;
}


- (void)prepareDeleteAlbum{
    
    MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"确定删除此相册吗" detailTitle:@"此操作不可撤销哦，请谨慎操作" contentView:nil leftButtonImageName:nil rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
    alert.titleLabel.textColor = UIColor.us_redColor;
    @weakify(self)
    alert.didClickIndexBlock = ^(NSInteger index) {
        @strongify(self)
        if (index == 1) {
            [self deleteAlbum];
        }
    };
    
    [alert show];
    
}

- (void)deleteAlbum{

    NSIndexPath *currentIndexPath = [self c_indexPath];
    if (!currentIndexPath) return;
    Album *album = self.list[currentIndexPath.item];
    
    @weakify(self)
    [[EMNetWork shareManager] em_post:API_AlbumDelete
                               params:@{@"albumId":album.albumId}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            return;
        }
        
        [USFeedbackTool notifySuccess];
        
        [USCoreDataStack.shared.context deleteObject:album];
        
        [USCoreDataStack.shared save];
        
        [self loadData];
        
    } fail:^{
        
    }];
    
}

- (void)makeAlbumTop{
    
    NSIndexPath *currentIndexPath = [self c_indexPath];
    if (!currentIndexPath) return;
    Album *album = self.list[currentIndexPath.item];
    
    [[EMNetWork shareManager] em_post:API_AlbumTop
                               params:@{@"albumId":album.albumId}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        
        album.topFlag = 1;
        
        [self loadData];
        
    } fail:^{
        
        
    }];
    
}

- (void)editAlbum{
    
    USAddPhotoAlbumController *vc = [USAddPhotoAlbumController new];

    NSIndexPath *currentIndexPath = [self c_indexPath];
    if (currentIndexPath) {
        Album *album = self.list[currentIndexPath.item];
        vc.album = album;
        self.selectIndexPath = currentIndexPath;
    }
   
    DTNavigationController *navc = [[DTNavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:navc animated:YES completion:nil];
    
    
}

#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
    USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
    emptyView.image = [UIImage imageNamed:@"Frame 112"];
    emptyView.title = @"还没有相册哦\n快来创建一个属于你们的吧！";
    emptyView.btnTitle = @"创建新相册";
    emptyView.userInteractionEnabled = YES;
    [emptyView.btn addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    return emptyView;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}


@end
